<template>
  <div class="project">
    <ListTab v-model="activeId" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <DataDisplay
        :data-list="statisticsList"
        class="mb16 mobile-data"
      />
      <div v-if="!showMobilePage" class="relative mb16">
        <FilterInput ref="FilterToolRef" v-model="paramsObj" :is-show-filter="isShowFilter" :filter-list="filterList" is-show-config show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div class="table-top-opeator-bar">
          <create-button v-if="hasRouteAuth('crm:cost:create') || isAdmin" :add-name="'新建成本'" :is-own-logic="true" style="margin-right: 10px" @click="openDialog()" />
          <i v-if="exportLoading" class="el-icon-loading mr5"/>
          <div class="button-container">
            <el-dropdown v-if="canEdit || canExport" trigger="click">
              <el-button class="more-button" size="small">批量操作 <i class="el-icon-caret-bottom"/></el-button>
              <el-dropdown-menu slot="dropdown" class="el-dropdown-menu-batch-set cost-dropdown">
                <el-dropdown-item v-if="(hasRouteAuth('crm:cost:batchExport') || isAdmin)" :disabled="exportLoading" class="export-item" @click.native="handleBatchExport">
                  批量导出
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleApproverBatchChange(ids)">
                  批量转交
                </el-dropdown-item>
                <el-dropdown-item v-if="activeId !== 1 && activeId !== 2 && (hasRouteAuth('crm:cost:batchApproval') || isAdmin)" @click.native="costApprovalDialog(HANDLE_ACTIVE.PASS_APPROVAL)">
                  批量审批
                </el-dropdown-item>
                <el-dropdown-item v-if="activeId !== 1 && activeId !== 2 && (hasRouteAuth('crm:cost:ignoreRecovery') || isAdmin) && (activeId === 0 || activeId === -1)" @click.native="costBatchStatus(HANDLE_ACTIVE.IGNORE, '' , true)">
                  批量忽略
                </el-dropdown-item>
                <el-dropdown-item v-if="activeId !== 1 && activeId !== 2 && (hasRouteAuth('crm:cost:ignoreRecovery') || isAdmin) && activeId === 5" @click.native="costBatchStatus(HANDLE_ACTIVE.RECOVER, '' , true)">
                  批量恢复
                </el-dropdown-item>
                <el-dropdown-item v-if="activeId !== 1 && activeId !== 2 && (hasRouteAuth('crm:cost:batchApprovalCancel') || isAdmin)" @click.native="costApprovalDialog(HANDLE_ACTIVE.CANCEL_APPROVAL)">
                  批量作废
                </el-dropdown-item>
                <el-dropdown-item v-if="(activeId !== 1 && activeId !== 2 && (hasRouteAuth('crm:cost:batchDelete') || isAdmin))" @click.native="openDeleteDialog(null)">
                  批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
      <btnGroup
        ref="btnGroupRef"
        :list="[{ label:'',exportApi:'/admin/cost/list/batchExport', exportName:'成本列表', type: 'export', notLoading:true }]"
        style="width: 0; height: 0;display:none;"
        @beginExport="beginExport"
        @onComplate="onComplate"
      />
      <div v-loading="listLoading" class="table-wrap" style="min-height: 300px">
        <u-table
          v-if="list.items.length > 0"
          ref="costTableRef"
          :data="list.items"
          :row-class-name="tableRowClassName"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            align="center"
            type="selection"
            fixed="left"
            width="50"/>
          <u-table-column align="left" label="成本编号" width="180">
            <template slot-scope="scope">
              <div class="light-word" @click="toCostDetail(scope.row)">
                <ToolTip :content="scope.row.costNum" is-can-click @handelClick="toCostDetail(scope.row)"/>
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单日期" width="110" prop="orderDate" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.orderDate">{{ scope.row.orderDate | standardFormat('YYYY/MM/DD') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="成本项" width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.costItemName"/>
            </template>
          </u-table-column>
          <u-table-column align="right" label="含税成本（元）" min-width="150" prop="taxCost" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxCost" :price="scope.row.taxCost / 100" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="供应商" width="220">
            <template slot-scope="scope">
              <div class="light-word" @click="toSupplierDetail(scope.row)">
                <ToolTip :content="scope.row.supplierName" is-can-click @handelClick="toSupplierDetail(scope.row)"/>
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="说明" width="160">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.costDescription"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="可抵扣税率" min-width="100" prop="discount">
            <template slot-scope="scope">
              <div v-if="scope.row.discount || scope.row.discount === 0">
                {{ scope.row.discount }} %
              </div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="审批状态" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalStatus || scope.row.approvalStatus === 0" class="dot-wrap">
                <span :style="{backgroundColor: getColor(scope.row.approvalStatus)}" class="dot"/>
                {{ scope.row.approvalStatus | costApprovalStatus }}
              </div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="成本状态" width="80">
            <template slot-scope="scope">
              <div
                v-if="scope.row.settlementStatus || scope.row.settlementStatus === 0"
                :class="{'light-word': scope.row.settlementStatus === 1 || scope.row.settlementStatus === 2}"
                class="dot-wrap"
                @click="toSettleDetail(scope.row)">
                <span :style="{backgroundColor: getCostColor(scope.row.settlementStatus)}" class="dot"/>
                {{ scope.row.settlementStatus | settlementStatusFilter }}
              </div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="关联订单" width="190" prop="isNotRelateOrder" sortable="custom">
            <template slot-scope="scope">
              <ToolTip v-if="scope.row.isNotRelateOrder" :content="scope.row.relatedOrderNum" is-can-click @handelClick="goDetail(scope.row)"/>
              <div v-else-if="canRlatedOrder(scope.row) && scope.row.costBelong === 0" class="project-num" @click="relatedOrderDialog(scope.row.id)"><span>关联订单</span></div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="品牌名称" width="140">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.theme"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单平台" width="120">
            <template slot-scope="scope">
              <div class="flex-center">
                <platformIcon :data="scope.row.orderPlatform" />
                <ToolTip :content="scope.row.orderPlatform" />
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="账号" width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.resourceName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="成本来源" width="90">
            <template slot-scope="scope">
              {{ scope.row.costBelong | costBelongFilter }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="封账状态" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.relatedOrderId && (scope.row.sealBillType || scope.row.sealBillType === 0)" class="dot-wrap">
                <span :style="{backgroundColor: getSealColor(scope.row.sealBillType)}" class="dot"/>
                {{ scope.row.sealBillType | setSealCostType }}
              </div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="封账月份" min-width="110" prop="costSealMonth" sortable="custom">
            <template slot-scope="scope">
              {{ formatMonth(scope.row.costSealMonth) }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="成本类型" width="120">
            <template slot-scope="scope">
              {{ scope.row.costType | costTypeFilter }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="申请人" width="90">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.departmentName"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="审批时间" width="160" prop="approvalDate" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalDate">{{ scope.row.approvalDate | standardFormat('YYYY/MM/DD HH:mm:ss') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" width="160" prop="createDate" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.createDate">{{ scope.row.createDate | standardFormat('YYYY/MM/DD HH:mm:ss') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" width="90">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex">
                <div class="button-text" @click="toDetail(scope.row)">查看</div>
                <el-dropdown
                  v-if="canSettlement(scope.row) ||
                    canEdit(scope.row) ||
                    canIgnore(scope.row) ||
                    canChangeApprover(scope.row) ||
                    (hasRouteAuth('crm:cost:ignoreRecovery') && scope.row.settlementStatus === 5) ||
                  canDelete(scope.row)">
                  <div class="el-dropdown-link">
                    <div class="button-text">更多<i class="el-icon-arrow-down"/></div>
                  </div>
                  <!-- 项目订单状态relatedProjectStatus: 5-已封存，需要禁用成本编辑和删除 -->
                  <el-dropdown-menu
                    slot="dropdown"
                    class="dropdown-wrap">
                    <el-dropdown-item v-if="canApproval(scope.row)" @click.native="costApprovalDialog(HANDLE_ACTIVE.PASS_APPROVAL, scope.row)">
                      <div>审批</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="canSettlement(scope.row)" @click.native="toSettlement(scope.row)">
                      <div>结算</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="canEdit(scope.row)" @click.native="openDialog('edit', scope.row)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="canIgnore(scope.row)" @click.native="costBatchStatus(HANDLE_ACTIVE.IGNORE, scope.row)">
                      <div>忽略</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="hasRouteAuth('crm:cost:ignoreRecovery') && scope.row.settlementStatus === 5" @click.native="costBatchStatus(HANDLE_ACTIVE.RECOVER, scope.row)">
                      <div>恢复</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="canChangeApprover(scope.row)" @click.native="handleApproverBatchChange(scope.row.id)">
                      <div>转交</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="canDelete(scope.row)" @click.native="openDeleteDialog(scope.row.id)">
                      <div>删除</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="canApprovalCancel(scope.row)" @click.native="costApprovalDialog(HANDLE_ACTIVE.CANCEL_APPROVAL, scope.row)">
                      <div>作废审批</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item @click.native="toDetail(scope.row)">
                  <div>查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="canApproval(scope.row)" @click.native="costApprovalDialog(HANDLE_ACTIVE.PASS_APPROVAL, scope.row)">
                  <div>审批</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="canSettlement(scope.row)" @click.native="toSettlement(scope.row)">
                  <div>结算</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="canEdit(scope.row)" @click.native="openDialog('edit', scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="canIgnore(scope.row)" @click.native="costBatchStatus(HANDLE_ACTIVE.IGNORE, scope.row)">
                  <div>忽略</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('crm:cost:ignoreRecovery') && scope.row.settlementStatus === 5" @click.native="costBatchStatus(HANDLE_ACTIVE.RECOVER, scope.row)">
                  <div>恢复</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="canChangeApprover(scope.row)" @click.native="handleApproverBatchChange(scope.row.id)">
                  <div>转交</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="canDelete(scope.row)" @click.native="openDeleteDialog(scope.row.id)">
                  <div>删除</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="canApprovalCancel(scope.row)" @click.native="costApprovalDialog(HANDLE_ACTIVE.CANCEL_APPROVAL, scope.row)">
                  <div>作废审批</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit"/>
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput ref="FilterToolRef" v-model="paramsObj" :is-show-filter="isShowFilter" :filter-list="filterList" is-show-config show-search-btn show-mobile-icon @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="moreOperatorList"
            show-mobile-icon
          />
          <createBtn v-if="hasRouteAuth('crm:cost:create') || isAdmin" text="新建成本" mobile-table @click.native="openDialog"/>
        </template>
        <template v-else>
          <SelectionNum :select-item="multipleSelectionAll" style="flex:1;" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
    <CreateEditCost ref="createEditCost" :cost-id="costId" :type="opreateType" :cost-belong-type="costBelongType" @handleClose="handleClose" @submit="fetchData(opreateType !== 'edit')"/>
    <RelatedOrderDialog ref="relatedOrder" :cost-id="costId" @relatedOrder="fetchData"/>
    <CostApprovalDialog
      ref="costApproval"
      :cost-ids="costIds"
      :type="approvalType"
      :is-batch="isBatch"
      :select-list="selectList"
      :params="formatParams()"
      @costApprovalhandle="costApprovalhandle" />
    <!-- 人员转交 -->
    <ApproverChange
      ref="approverChangeDialog"
      :business-type="BUSINESS_TYPE.COST"
      :ids="approverChangeIds"
      append-to-body
      @changeCallBack="fetchData"
    />
  </div>
</template>
<script>
// api
import {
  getCostSettlementStatus,
  getCostList,
  deleteCost,
  costBatchStatus,
  getCostStatistics } from '@/api/costManage';
import { getDepartment } from '@/api/project';
import { costList } from '@/api/config';
import { platformList } from '@/api/select';
import ListTab from '@/components/ListTab';
import createButton from '@/components/CreateButton';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import projectOpeator from '@/components/ProjectComponent/model/projectOpeator';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import { costType, approvalStatus, sealingStateOption, settlementStatusOptions } from './model/selectData';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import platformIcon from '@/components/Common/platformIcon';
import ApproverChange from '@/components/Common/auditProcess/approverChange';
// filter
import {
  settlementStatusFilter,
  costBelongFilter,
  costTypeFilter,
  costApprovalStatus,
  setSealCostType } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { standardFormat } from '@/filters/date';
import setting from '@/assets/setting.png';
import { hasRouteAuth } from '@/utils/permission';
import { paramsFormat } from '@/utils/paramsFormat';
import { BUSINESS_TYPE } from '@/utils/const/process';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import isAdmin from '@/mixins/isAdmin';
import costSet from '@/mixins/costSet';
import paramsDateFormat from '@/mixins/paramsDateFormat';
import costOperate from '@/mixins/costToUrl';
import { HANDLE_ACTIVE,
  SETTLEMENT_STATUS,
  APPROVAL_STATUS,
  SEALING_STATUS
} from '@/utils/const/cost';
import mobileTable from '@/mixins/mobileTable';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import icon_26 from '@/assets/dataDisplay/icon_26.png';
import icon_27 from '@/assets/dataDisplay/icon_27.png';
import icon_28 from '@/assets/dataDisplay/icon_28.png';
import icon_29 from '@/assets/dataDisplay/icon_29.png';

export default {
  components: {
    ListTab,
    createButton,
    EmptyPlaceholder,
    projectOpeator,
    btnGroup,
    DataDisplay,
    createBtn,
    MoreOpeator,
    platformIcon,
    ApproverChange,
    CreateEditCost: () => import('@/components/Cost/createCost'),
    RelatedOrderDialog: () => import('@/components/Cost/relatedOrderDialog')
  },
  filters: {
    moneyFilter,
    settlementStatusFilter,
    costBelongFilter,
    costTypeFilter,
    standardFormat,
    costApprovalStatus,
    setSealCostType },
  mixins: [
    tableSelections,
    isAdmin,
    costSet,
    paramsDateFormat,
    TableAdaptive,
    costOperate,
    mobileTable],
  data() {
    return {
      BUSINESS_TYPE,
      setting,
      isUmyTable: true,
      tabList: [],
      activeId: -1,
      listLoading: false,
      opeatorLoading: false,
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      paramsObj: {},
      departmentOption: [],
      costItem: [],
      summaryPublish: '',
      summaryBack: '',
      isShowFilter: false,
      tableRefName: 'costTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      ids: '',
      approverChangeIds: '', // 转交id
      opreateType: '',
      costId: 0,
      selectList: [], // 列表已选字段
      relateOrderStatus: [
        { value: 0, label: '未关联' },
        { value: 1, label: '已关联' }],
      isBatch: 0,
      costIds: '',
      statisticsList: [],
      platformTypeOption: [],
      dateDataAttrName: [
        {
          attr: 'createTime',
          start: 'createDateStart',
          end: 'createDateEnd',
          endType: 1
        },
        {
          attr: 'approvalTime',
          start: 'approvalDateStart',
          end: 'approvalDateEnd',
          endType: 1
        },
        {
          attr: 'orderDate',
          start: 'orderDateStart',
          end: 'orderDateEnd',
          endType: 1
        }, {
          attr: 'costSealMonth',
          start: 'sealMonthStart',
          end: 'sealMonthEnd',
          type: 'time'
        }
      ],
      HANDLE_ACTIVE,
      isBatchAll: false,
      operateApprovalType: '',
      operateStatus: '',
      rangeKeyArr: [{
        attr: 'taxCost',
        start: 'taxCostStart',
        end: 'taxCostEnd',
        type: 'moneyFixed'
      }],
      exportLoading: false,
      costBelongType: -1
    };
  },
  computed: {
    activeName() {
      const item = this.tabList.find(i => i.id === this.activeId);
      return item ? item.name : '全部';
    },
    arrayKeyArr() {
      return ['costItemName', 'departmentId', 'approvalStatus', 'sealBillType', 'settlementStatus', 'orderPlatform'];
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'costNum', name: '成本编号', labelWidth: '70px', type: 'input' },
        { keyword: 'supplierName', name: '供应商', labelWidth: '70px', type: 'input' },
        { keyword: 'costDescription', name: '说明', labelWidth: '70px', type: 'input' },
        { keyword: 'relatedOrderNum', name: '关联订单', labelWidth: '70px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '70px', type: 'input' },
        { keyword: 'theme', name: '品牌名称', labelWidth: '70px', type: 'input' },
        { keyword: 'resourceName', name: '账号', labelWidth: '70px', type: 'input' },
        // 下拉
        { keyword: 'departmentId', name: '所属部门', type: 'mulSelect', isSearch: true, options: this.departmentOption }, // 可搜索下拉
        { keyword: 'costItemName', name: '成本项', type: 'mulSelect', options: this.costItem },
        { keyword: 'costBelong', name: '成本来源', type: 'select', options: [
          { value: 0, label: '渠道订单' }, { value: 1, label: '项目订单' }, { value: 2, label: '商务订单' },
          { value: 3, label: '营销授权' }, { value: 5, label: '项目渠道单' }] },
        { keyword: 'costType', name: '成本类型', type: 'select', options: costType },
        { keyword: 'isNotRelateOrder', name: '关联状态', type: 'select', options: this.relateOrderStatus },
        { keyword: 'approvalStatus', name: '审批状态', type: 'mulSelect', options: approvalStatus },
        { keyword: 'sealBillType', name: '封账状态', type: 'mulSelect', options: sealingStateOption },
        { keyword: 'settlementStatus', name: '成本状态', type: 'mulSelect', options: settlementStatusOptions },
        { keyword: 'orderPlatform', name: '下单平台', type: 'mulSelect', options: this.platformTypeOption },
        // 日期
        { keyword: 'taxCost', name: '含税成本', labelWidth: '70px', type: 'inputRange' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'approvalTime', name: '审批时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'orderDate', name: '下单日期', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'costSealMonth', name: '封账月份', labelWidth: '70px', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM' }
      ];
      return arr;
    },
    moreOperatorList() {
      return [
        { label: '批量导出', auth: hasRouteAuth('crm:cost:batchExport') || isAdmin, handelClick: this.handleBatchExport },
        { label: '批量审批', auth: (this.activeId !== 1 && this.activeId !== 2 && (hasRouteAuth('crm:cost:batchApproval') || isAdmin)), handelClick: () => this.costApprovalDialog(HANDLE_ACTIVE.PASS_APPROVAL) },
        { label: '批量忽略', auth: (this.activeId !== 1 && this.activeId !== 2 && (hasRouteAuth('crm:cost:ignoreRecovery') || isAdmin) && (this.activeId === 0 || this.activeId === -1)), handelClick: () => this.costBatchStatus(HANDLE_ACTIVE.IGNORE, '', true) },
        { label: '批量恢复', auth: (this.activeId !== 1 && this.activeId !== 2 && (hasRouteAuth('crm:cost:ignoreRecovery') || isAdmin) && this.activeId === 5), handelClick: () => costBatchStatus(HANDLE_ACTIVE.RECOVER, '', true) },
        { label: '批量作废', auth: (this.activeId !== 1 && this.activeId !== 2 && (hasRouteAuth('crm:cost:batchApprovalCancel') || isAdmin)), handelClick: () => this.costApprovalDialog(HANDLE_ACTIVE.CANCEL_APPROVAL) },
        { label: '批量删除', auth: (this.activeId !== 1 && this.activeId !== 2 && (hasRouteAuth('crm:cost:batchDelete') || isAdmin)), handelClick: () => this.openDeleteDialog(null) }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 256 : 246;
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'costDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.paramsObj = {};
        this.clearMixinSelection();
        this.isShowFilter = false;
        this.activeId = this.$route.query.settlementStatus !== undefined ? Number(this.$route.query.settlementStatus) : -1;
        this.fetchData(true);
      }
    } else {
      // this.page = localStorage.getItem('projectPage');
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
  },
  created() {
    this.getDepartmentData();
    this.getCostItemList();
    this.platformTypeList();
  },
  methods: {
    hasRouteAuth,
    isCreator(row) {
      return this.userInfo.id === row.creatorId;
    },
    // 获取下单平台选项
    async platformTypeList() {
      this.platformTypeOption.push({ value: -1, label: '全部' });
      try {
        const result = await platformList();
        const option = result.data.map(item => {
          return {
            value: item.id,
            label: item.value
          };
        });
        this.platformTypeOption.push(...option);
      } catch (error) {
        console.log(error);
      }
    },
    formatMonth(str = '') {
      if (!str) return '--';
      return str.replace(/-/g, '/');
    },
    canSettlement({ settlementStatus: sStatus, approvalStatus: aStatus }) {
      // 成本结算状态为待结算 审核状态不等于拒绝
      return sStatus === SETTLEMENT_STATUS.TO_BE_SETTLED && approvalStatus !== APPROVAL_STATUS.REFUSE;
    },
    canIgnore({ settlementStatus: sStatus }) {
      return sStatus === SETTLEMENT_STATUS.TO_BE_SETTLED && (hasRouteAuth('crm:cost:ignoreRecovery') || this.isAdmin);
    },
    // 是否允许转交， 权限 + 待结算/结算中
    canChangeApprover(rowData) {
      return (hasRouteAuth('crm:cost:approverChange') || rowData.creatorId === this.userInfo.id) && [0, 2].includes(rowData.settlementStatus);
    },
    canRlatedOrder({ settlementStatus: sStatus, relatedOrderId }) {
      return !relatedOrderId || (relatedOrderId && sStatus !== SETTLEMENT_STATUS.COMPLETED);
    },
    commonAuth(sStatus, relatedProjectStatus, relatedOrderId, costBelong, aStatus, sealBillType) {
      // v3.2.9 去除成本来源不能为项目订单和项目渠道单的限制
      /* 成本审核状态不为成本结算状态-已完成 &&
        ( ((结算状态为成本结算状态-待结算 || 已忽略) && 没有关联订单) ||
          (有关联订单 && 关联订单不为已封存 && (结算状态为成本结算状态-待结算 || 已忽略) ) &&
          成本封账状态不为已封账或封账中
        )
        */
      /* return aStatus !== SETTLEMENT_STATUS.COMPLETED &&
        (((sStatus === SETTLEMENT_STATUS.TO_BE_SETTLED || sStatus === SETTLEMENT_STATUS.IGNORED) &&
        !relatedOrderId) || (relatedOrderId && relatedProjectStatus !== 5 &&
        (sStatus === SETTLEMENT_STATUS.TO_BE_SETTLED || sStatus === SETTLEMENT_STATUS.IGNORED)) &&
        sealBillType !== SEALING_STATUS.COMPLETED && sealBillType !== SEALING_STATUS.SEALING); */
      return aStatus !== SETTLEMENT_STATUS.COMPLETED && (
        (!relatedOrderId && [SETTLEMENT_STATUS.TO_BE_SETTLED, SETTLEMENT_STATUS.IGNORED].includes(sStatus)) ||
        (relatedOrderId && relatedProjectStatus !== 5 && [SETTLEMENT_STATUS.TO_BE_SETTLED, SETTLEMENT_STATUS.IGNORED].includes(sStatus)) &&
        ![SEALING_STATUS.COMPLETED, SEALING_STATUS.SEALING].includes(sealBillType)
      );
    },
    canEdit({ settlementStatus: sStatus, relatedProjectStatus, relatedOrderId, costBelong, approvalStatus: aStatus, sealBillType }) {
      return (hasRouteAuth('crm:cost:edit') || this.isAdmin) &&
      this.commonAuth(sStatus, relatedProjectStatus, relatedOrderId, costBelong, aStatus, sealBillType);
    },
    canDelete({ settlementStatus: sStatus, relatedProjectStatus, relatedOrderId, costBelong, approvalStatus: aStatus, sealBillType, creatorId }) {
      return (hasRouteAuth('crm:cost:delete') || this.isAdmin || this.isCreator({ creatorId })) &&
      this.commonAuth(sStatus, relatedProjectStatus, relatedOrderId, costBelong, aStatus, sealBillType);
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        // 2.8.4关联订单的sortName传order_id
        this.sortName = a.prop === 'isNotRelateOrder' ? 'order_id' : a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    // 获取成本管理下包含的部门
    getDepartmentData() {
      const params = {
        type: 6
      };
      getDepartment(params).then(res => {
        if (res.data) {
          res.data.unshift({ value: -2, label: '--' });
          this.departmentOption = res.data;
        }
      });
    },
    // 获取成本项列表
    getCostItemList() {
      costList({ getAll: 1 }).then(res => {
        if (res.data) {
          const costItem = res.data.items;
          const costItemList = [];
          costItem.forEach(item => {
            if (!costItemList.find(cost => cost.label === item.costName)) {
              const obj = {
                value: item.costName,
                label: item.costName
              };
              costItemList.push(obj);
            }
          });
          this.costItem = costItemList;
        }
      });
    },
    formatParams(sendPageConfig = true) {
      const { sortName, sortType, page, perPage, activeId, paramsObj, activeName } = this;
      let params = JSON.parse(JSON.stringify(paramsObj));
      // 设置tab
      if (activeName !== '全部') params.settlementStatus = activeId;
      // 时间处理
      this.paramsDateFormat(this.dateDataAttrName, params, 's');
      params = paramsFormat(params);
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (sendPageConfig) {
        params.page = page;
        params.perPage = perPage;
      }
      if (sortName) {
        params.sortName = sortName;
        params.sortType = sortType;
      }
      // if (params.costItemName && this.costItem.length) {
      //   params.costItemName = this.costItem.find(item => item.value === params.costItemName).label;
      // }
      return params;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.getTabList(params);
      this.getCostData(params);
      this.listLoading = true;
      if (this.isBatchAll) params.returnIds = true;
      getCostList(params).then(({ data = {}} = {}) => {
        const { items } = data;
        if (this.isBatchAll) {
          // 批量操作事件 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          if (this.operateApprovalType === 'ignoreRecovery') this.costBatchStatusRequest(this.operateStatus, items);
          if (this.operateApprovalType === 'approval') this.$refs.costApproval.approvalRequest(this.operateStatus, items);
          this.isBatchAll = false;
        } else {
          data.items.map(item => {
            if (item.department && item.department.length) item.departmentName = item.department.map(i => i.name).join(',');
            return item;
          });
          this.list = data;
          if (this.setSelectRow) this.setSelectRow(data.items);
        }
      }).catch(e => {
        console.error(e);
      }).finally(() => {
        this.list.isInit = false;
        this.listLoading = false;
      });
    },
    // 获取顶部Tab列表（成本状态）
    async getTabList(params = {}) {
      try {
        const result = await getCostSettlementStatus(params);
        const { code, data = [] } = result;
        if (code === 200) {
          // 只展示待结算、结算中的数量；
          data.forEach((tab) => {
            tab.num = tab.id === 0 || tab.id === 2 ? tab.num : 0;
          });
          this.tabList = data;
        }
      } catch (error) {
        this.tabList = [
          { id: -1, name: '全部', num: 0 },
          { id: 0, name: '待结算', num: 0 },
          { id: 2, name: '结算中', num: 0 },
          { id: 1, name: '已完成', num: 0 },
          { id: 5, name: '已忽略', num: 0 }
        ];
        console.log(error);
      }
    },
    // 恢复/忽略操作
    costBatchStatus(status, item = {}, isBatchOpt = false) {
      const { id } = item;
      if (status === 5 && this.selectList.find(i => i.settlementStatus === 5)) {
        this.$message.warning('所选成本包含已忽略成本，请重新选择');
        return false;
      }
      if (status === 5 && this.selectList.find(i => i.settlementStatus === 1 || i.settlementStatus === 2)) {
        this.$message.warning('所选成本包含结算中或已完成的成本，请重新选择');
        return false;
      }
      const isBatchAll = this.selectList.length <= 0 && isBatchOpt;
      this.$confirm(
        `请确认是否${id ? '' : '批量'}${status === 5 ? '忽略' : '恢复'}该成本？`,
        '',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true,
          type: 'warning',
          customClass: ' del-message del-message-cancel',
          iconClass: 'del-icon'
        }
      ).then(() => {
        if (isBatchAll) {
          this.isBatchAll = true;
          this.operateApprovalType = 'ignoreRecovery';
          this.operateStatus = status;
          this.fetchData();
        } else {
          this.costBatchStatusRequest(status, id);
        }
      });
    },
    async costBatchStatusRequest(status, id) {
      try {
        const ids = id instanceof Array ? id.join(',') : id;
        const data = { status, ids: ids || this.ids };
        const result = await costBatchStatus(data);
        const { code, message } = result;
        if (code === 501) {
          this.$message.error(message);
          return false;
        }
        this.costApprovalhandle();
      } catch (error) {
        console.log(error);
      }
    },
    handleTabClick(id) {
      this.activeId = id;
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.fetchData(true);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.fetchData(true);
    },
    // 多选
    tableSelectionChange(e) {
      this.selectList = e;
      this.ids = e.map(item => {
        return item.id;
      }).join(',');
    },
    // 跳转到供应商结算页 id: 供应商id, costItemId:传成本项id，costId:成本id，relatedOrderId:关联订单id, name: 成本项名称, orderId: 订单编号
    toSettlement({ id, costItemId, relatedOrderId, supplierId, costItemName, relatedOrderNum, costBelong }) {
      if (!supplierId) {
        this.$message.warning('该成本未填供应商，无法发起结算');
        return false;
      }
      this.$router.push({
        name: 'supplierCreate', // supplierDetail
        query: {
          id: supplierId, // 供应商id，查找信息
          // （第一步）成本选择阶段
          costItemId, // 成本项id，选中该成本项
          name: costItemName, // 成本项名称，选中该成本项
          // （第二步）审核项选择阶段
          relatedOrderId, // 关联订单id，选中该关联订单（如果有的话）
          costId: id, // 成本id，选中该成本
          orderId: relatedOrderNum || '', // 订单编号，查找该订单，并选中该订单
          costBelong: costBelong // 成本归属，选中该成本归属
        }
      });
    },
    // 打开弹窗用于新增或修改 编辑，type: edit
    openDialog(type, row) {
      this.costBelongType = row ? row.costBelong : -1;
      if (row) {
        this.costId = row.id || 0;
      }
      this.opreateType = this.showMobilePage && type !== 'edit' ? '' : type;
      this.$refs.createEditCost.openDialog(row ? row.costBelong : '');
      // this.$refs.createEditCost.formatSupplierName(supplierId, supplierName);
    },
    // 打开关联订单弹窗
    relatedOrderDialog(costId) {
      this.costId = costId;
      this.$refs.relatedOrder.openDialog();
    },
    // 删除成本
    openDeleteDialog(id = null) {
      if (!this.ids && !id) {
        this.$message.error('请选择成本');
        return;
      }
      if (this.selectList.find(i => i.settlementStatus === 1 || i.settlementStatus === 2)) {
        this.$message.warning('所选成本包含结算中或已完成的成本，请重新选择');
        return false;
      }
      if (this.selectList.find(i => i.approvalStatus === 1)) {
        this.$message.warning('所选成本包含已通过的成本，请重新选择');
        return false;
      }
      if (this.selectList.find(i => i.sealBillType === 1 || i.sealBillType === 2)) {
        this.$message.warning('所选成本包含封账中或已完成的成本，请重新选择');
        return false;
      }
      let ids = null;
      ids = this.ids;
      const Num = ids.split(',').length;
      if (id) {
        ids = `${id}`;
      }
      this.$confirm(id ? `请确认是否删除该成本？` : `请确认是否批量删除${Num}个成本？`, {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        this.handleBatchDelete(ids);
      }).catch(() => {
        return false;
      });
    },
    // 批量删除
    handleBatchDelete(ids = null) {
      deleteCost({ ids }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
        this.$message.success('删除成功');
        this.clearMixinSelection();
        this.fetchData();
      }).catch((err) => {
        console.log(err);
      });
    },
    handleSizeChange(perPage) {
      this.perPage = perPage;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handleClose(value) {
      this.costBelongType = -1;
      // 组件的关闭方法执行比$emit快 注意重置opreateType的时机要放在最后 用于编辑后跳转的页面应该是当前页
      setTimeout(() => {
        this.opreateType = value;
      }, 1000);
    },
    toDetail(item) {
      this.$router.push({
        name: 'costDetail',
        params: { id: item.id }
      });
    },
    goDetail(item) {
      const id = item.relatedOrderId;
      let routeUrl = null;
      let params = {};
      if (item.costBelong === 0) {
        // 渠道订单
        params = {
          name: 'orderDetail',
          params: { orderId: id }
        };
      } else if (item.costBelong === 1) {
        // 项目订单
        params = {
          name: 'projectDetail',
          params: { id: id }
        };
      } else if (item.costBelong === 2) {
        // 商务订单
        params = { name: 'mengliOrderDetail', params: { id: id }, query: { type: 0 }};
      } else if (item.costBelong === 3) {
        // 营销授权
        params = { name: 'mengliOrderDetail', params: { id: id }, query: { type: 1 }};
      } else if (item.costBelong === 5) {
        // 项目渠道单
        params = { name: 'projectChildDetail', params: { id: id }};
      }
      routeUrl = this.$router.resolve(params);
      if (routeUrl) window.open(routeUrl.href, '_blank');
    },
    // 批量导出
    handleBatchExport() {
      const params = this.formatParams();
      this.ids && (params.ids = this.ids);

      let msg = '<div>是否确定导出数据？</div>';
      if (!params.ids) {
        msg = msg + `<div style="color: red;font-size: 14px;">单次最多导出5000条</div>`;
      }
      this.$refs['btnGroupRef'].btnExport(params, msg);
    },
    // 批量转交
    handleApproverBatchChange(ids) {
      if (!ids) {
        this.$message.warning('请选择需要转交的成本');
        return;
      }
      this.approverChangeIds = ids + '';
      this.$refs['approverChangeDialog'].dialogVisible = true;
    },
    beginExport() {
      this.exportLoading = true;
    },
    onComplate() {
      this.exportLoading = false;
    },
    // 审批操作成功后的交互
    costApprovalhandle({ operateApprovalType, isBatchAll, approvalStatus } = {}) {
      if (isBatchAll) {
        this.isBatchAll = isBatchAll;
        this.operateApprovalType = operateApprovalType;
        this.operateStatus = approvalStatus;
      } else {
        // 操作成功清除选项
        this.clearMixinSelection();
        this.$message.success('操作成功');
      }
      this.fetchData();
    },
    // 获取统计数据
    async getCostData(paramsObj = '') {
      try {
        const params = paramsObj ? JSON.parse(JSON.stringify(paramsObj)) : this.formatParams(false);
        const { page, perPage } = params;
        if (page) delete params.page;
        if (perPage) delete params.perPage;
        const res = await getCostStatistics(params);
        const { code, data = {}} = res;
        if (code === 200) {
          const { yesterdayCostCount, yesterdayCostAmount, totalCostCount, totalCostAmout } = data;
          this.statisticsList = [
            { data: yesterdayCostCount, label: '昨日成本数', icon: icon_26, isMoney: false },
            { data: yesterdayCostAmount / 100, label: '昨日成本金额', icon: icon_27 },
            { data: totalCostCount, label: '总成本数', icon: icon_28, isMoney: false },
            { data: totalCostAmout / 100, label: '总成本金额', icon: icon_29 }
          ];
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/placeholder.scss';
.dot-wrap {
  @extend %dot-wrap;
}
.el-icon-loading:before{
  font-size: 14px;
}
.export-item{
  border-bottom:1px solid #DDDDDD;
}
.project {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .project-num {
      color: #406EFF;
      span {
        cursor: pointer;
      }
    }
  }
}
.batch-set {
  background: #406eff;
  border-color: #406eff;
  color: #fff;
  height: 32px;
}
.dropdown-wrap {
  margin-top: 5px;
  padding: 0;
  .el-dropdown-menu__item {
    width: 100px;
    text-align: center;
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  margin-left: 6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
.max-width-200 {
  max-width: 200px;
}
.empty-placeholder-container {
  padding-top: 100px;
}
.more-button {
  padding: 0;
  width: 96px;
  height: 32px;
  border: 1px solid #DDD;
  border-radius: 4px;
  color: #666;
  background: #fff;

}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
</style>
<style lang="scss">
.el-dropdown-menu-batch-set.cost-dropdown {
  margin-bottom: 5px;
  padding: 0;
  .el-dropdown-menu__item {
    padding: 0 10px;
    min-width: 100px;
    max-width: 200px;
    text-align: center;
  }
  .meidum-export-btn {
    margin-right: 0px;
    height: 36px;
    color: inherit;
    background: none;
  }
}
</style>
